<?php
//=========================
//Quan Van Sinh
//sinhnvb@vietnambiz.com, qvsinh@yahoo.com
//=========================

function listPropertyCategoryByParent($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_property WHERE  cat_parent = ".intval($parent_id)." ORDER BY cat_order,cat_id");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
    }
    return $trees;
}
function get_property_contact() {

    global $db;
    if(isset($_SESSION['mem_property_id']) && intval($_SESSION['mem_property_id'])>0) {
        $sql = "SELECT * FROM property_contact WHERE property_id=".intval($_SESSION['mem_property_id']);

        $qr=$db->query_first($sql);

        return $qr;
    }

}

function getCategoryType() {
    global $db,$CONFIG;
    if(isset($_REQUEST['type'])) {
        $cat_parent = intval($_REQUEST['type']);
    }else {
        $cat_parent = 1;
    }

    $rsCatProperty = $db->query("SELECT cat_id,cat_title FROM cat_property WHERE cat_parent=$cat_parent ORDER BY cat_order");
    $option = '<option value="0">[Chọn danh mục]...</option>';
    while($rs=$db->fetch_array($rsCatProperty)) {
        if(isset($_REQUEST['cat_id']) && $_REQUEST['cat_id']==$rs['cat_id']) {
            $option .= '<option selected="selected" value="'.$rs['cat_id'].'">'.$rs['cat_title'].'</option>';
        }else {
            $option .= '<option value="'.$rs['cat_id'].'">'.$rs['cat_title'].'</option>';
        }
    }
    echo $option;
}

function getAjaxGeographic() {
    global $db;
    if(isset($_REQUEST['geo'])) {
        $geo_parent = intval($_REQUEST['geo']);
    }else {
        $geo_parent = 1;
    }
    if($geo_parent==1 || $geo_parent==2 || $geo_parent==3) {
        $option = '<option value="0">[Tỉnh/Thành phố]...</option>';
    }else {
        $option = '<option value="0">[Quận/Huyện]...</option>';
    }
    if(intval($geo_parent)>-1) {
        $rsGeoProperty = $db->query("SELECT geo_id,geo_title FROM geographic WHERE geo_parent=$geo_parent ORDER BY geo_title");
        while($rs=$db->fetch_array($rsGeoProperty)) {
            if(isset($_REQUEST['geo_id'])) {
                if($arrGeoID[0]==$rs['geo_id'] || $arrGeoID[1]==$rs['geo_id']) {
                    $option .= '<option selected="selected" value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
                }else {
                    $option .= '<option value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
                }
            }else {
                $option .= '<option value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
            }
        }
    }
    echo $option;
}

function listAllPropertyGeographicByParent($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM geographic WHERE  geo_parent = ".intval($parent_id)." ORDER BY geo_title");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['geo_parent']==0) {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$space.$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }
    }
    return $trees;
}

function getGeographicIdParentIdByChildId($childId) {
    global $db;
    $rs = $db->query_first("SELECT geo_id,geo_parent FROM geographic WHERE  geo_id = ".intval($childId));
    $rsArea = $db->query_first("SELECT geo_id,geo_parent FROM geographic WHERE  geo_id = ".intval($rs['geo_parent']));
    $rs['root'] = $rsArea['geo_parent'];
    $rs['city'] = $rs['geo_parent'];
    $rs['district'] = $rs['geo_id'];
    return $rs;
}

function checkPropertyLinkExist($propertyLink) {
    global $db;
    $rs = $db->query_first("SELECT id,title_link FROM property WHERE title_link='$propertyLink'");
    if(intval($rs['id'])>0) {
        $propertyLink = $rs['title_link'].'-'.rand(0,9);
        checkPropertyLinkExist($propertyLink);
    }
    return $propertyLink;
}

function getStatus($property_id) {
    global $db;
    $rs = $db->query_first("SELECT status FROM property WHERE id=$property_id");
    if($rs) {
        return $rs['status'];
    }else {
        return 'draft';
    }
}

function postPropertyComplete() {
    global $db,$params,$CONFIG,$CONFIG_MEMBER_LINK;
    if(isset($_POST['title']) && isset($_POST['type'])) {
        $data = array();
        if($_POST['type']==2) {
            $data['type'] = 'rent';
        }else {
            $data['type'] = 'sell';
        }
        if(intval($_POST['cat_id'])==0) {
            $CONFIG["error_message"] .= "<li>[Bạn chưa chọn danh mục].</li>";
        }
        if(trim($_POST['title'])=='') {
            $CONFIG["error_message"] .= "<li>[Bạn chưa chọn tiêu đề].</li>";
        }
        $arrGeoId = $_POST['geo_id'];
        $geo_id = intval($arrGeoId[1]);
        if($geo_id==0) {
            $CONFIG["error_message"] .= "<li>[Bạn chưa chọn quận/huyện].</li>";
        }

        if($_POST['noPrice']=='yes') {
            $data['price'] = 0;
        }else {
            $data['price'] = intval($_POST['price']);
            if(intval($_POST['price'])<=0) {
                $data['price'] = 0;
                //$CONFIG["error_message"] .= "<li>Bạn chưa nhập giá hoặc giá không được nhỏ hơn 0.</li>";
            }else {
                $data['price'] = intval($_POST['price']);
            }
        }
        if(trim($_POST['description'])=='') {
            $CONFIG["error_message"] .= "<li>[Bạn chưa nhập miểu tả bất động sản].</li>";
        }
        $create_date = date('Y-m-d H:i:s');

        $data['title'] = $_POST['title'];
        $data['cat_id'] = $_POST['cat_id'];
        $data['geo_id'] = $arrGeoId[1];
        $data['title_link'] = create_link($_POST['title']);
        $data['title_link'] = checkPropertyLinkExist($data['title_link']);
        $data['price'] = intval($_POST['price']);

        $data['member_id'] = $_SESSION['login']['id'];
        $data['last_edit'] = $create_date;
        $data['direction'] = $_POST['direction'];
        $data['area_use'] = floatval($_POST['area_use']);

        $data['legal_doc'] = $_POST['legal_doc'];

        $data['area_campus_width'] = floatval($_POST['area_campus_width']);
        $data['area_campus_depth'] = floatval($_POST['area_campus_depth']);
        $data['area_build'] = floatval($_POST['area_build']);
        $data['way'] = floatval($_POST['way']);
        $data['sittingroom'] = intval($_POST['sittingroom']);
        $data['bathroom'] = intval($_POST['bathroom']);
        $data['bedroom'] = intval($_POST['bedroom']);
        $data['kitchen'] = intval($_POST['kitchenroom']);
        $data['gara_oto'] = $_POST['gara_oto'];
        $data['build_year'] = intval($_POST['build_year']);
        $data['repair_year'] = $_POST['repair_year'];
        $data['org_price'] = $_POST['org_price'];
        if(isset($_POST['date_price']) && trim($_POST['date_price'])!='') {
            $data['date_price'] = $_POST['date_price'];
        }
        $data['description'] = $_POST['description'];
        $data['floor'] = intval($_POST['floor']);
        $data['map'] = $_POST['map'];
        $data['lang']=$_SESSION['lang'];       
        $data['order_num'] =  0;
        if($CONFIG["error_message"]=='') {

            //remove images being deleted
            $arrRemoveImage = $_POST['removeImages'];
            for($i=0;$i<count($arrRemoveImage);$i++) {
                if(intval($arrRemoveImage[$i])>0) {
                    $imageName = getPropertyImageNameByImageId($arrRemoveImage[$i]);
                    $db->exec_delete('property_image',"id=".$arrRemoveImage[$i]);
                    if(file_exists($upload_dir.'/'.$imageName)) {
                        unlink($upload_dir.'/'.$imageName);
                    }
                    for($s=0;$s<count($thumbSize);$s++) {// start create thumbnail
                        $upload_dir_thumb = $upload_dir.'/thumb-'.$thumbSize[$s];
                        $imageThumb = $upload_dir_thumb.'/'.$imageName;
                        if(file_exists($imageThumb)) {
                            unlink($imageThumb);
                        }
                    }
                }
            }

            $actionType = $_POST['stepAction'];
            $url='';
            if($actionType=='save') {
                if(isset($params[2]) && intval($params[2])>0) {
                    $data['status'] = getStatus(intval($params[2]));
                    if($data['status'] =="pending")
                        $url=get_link('member', $CONFIG_MEMBER_LINK['manage-pending-property']);
                    else
                        $url=get_link('member', $CONFIG_MEMBER_LINK['manage-posted-property']);
                }else {
                    $data['status'] = 'draft';
                    $url=get_link('member', $CONFIG_MEMBER_LINK['manage-draft-property']);
                }

            }else {//bam nut hoan thanh
                if(isset($params[2]) && intval($params[2])>0) {
                    $data['status'] = getStatus(intval($params[2]));
					if($data['status']=='draft'){
						$data['status'] = 'pending';
					}
                }else {
                    $data['status'] = 'pending';
                }
                $url=get_link('member', $CONFIG_MEMBER_LINK['post-property-success']);
            }
            $data['create_date'] = $create_date;
            $data_contact = array();

            $data_contact['name'] = $_POST['contact_name'];
            $data_contact['email'] = $_POST['contact_email'];
            $data_contact['address'] = $_POST['contact_address'];
            $data_contact['phone'] = $_POST['contact_phone'];
            $data_contact['mobile'] = $_POST['contact_mobile'];

            if(isset($params[2]) && intval($params[2])>0) {
                $db->exec_update('property', $data,"id=".intval($params[2]));
                $propertyId = intval($params[2]);
                $data_contact['property_id'] =$propertyId;
                $db->exec_update('property_contact', $data_contact,"property_id=".intval($params[2]));
            }else {
                $db->exec_insert('property', $data);
                $propertyId = mysql_insert_id();
                $data_contact['property_id'] =$propertyId;
                $db->exec_insert('property_contact', $data_contact);
            }

            $images = $_FILES['memberImages'];
            $thumbSize = $CONFIG['thumb_size_property'];
            $upload_dir = $CONFIG ['upload_dir'].'/images/property/pub-'.$_SESSION["login"]["id"].'/'.date("Y").'/'.date("m");
            $upload_url = '/uploads/images/property/pub-'.$_SESSION["login"]["id"].'/'.date("Y").'/'.date("m").'/thumb-'.$thumbSize[0];
            $now = time();
            if($images['size'][0]!='') {
                $checkFirstImage = 1;
                for($i=0;$i<count($images['size']);$i++) {
                    if ((($images["type"][$i] == 'image/gif') || ($images["type"][$i] == 'image/jpeg')|| ($images["type"][$i] == 'image/png') || ($images["type"][$i] == 'image/jpg')) && ($images["size"][$i] < 2000000)) {
                        $arrImageNameExplode = explode('.', $images["name"][$i]);
                        $imageExtention = $arrImageNameExplode[(count($arrImageNameExplode)-1)];
                        $filename = $now.'-'.rand(0,999999).'.'.strtolower($imageExtention);
                        if (!file_exists($upload_dir)) {
                            if(!mkdir($upload_dir, 0777,true)) {
                                $CONFIG["error_message"] .= "<li>Can not create directory, please check permission.</li>";
                            }
                        }
                        if (move_uploaded_file($images["tmp_name"][$i],$upload_dir."/".$filename)) {
                            if($checkFirstImage==1) {
                                $proThumb = $upload_url."/".$filename;
                                $sqlUpdateProperty = "UPDATE property SET thumb='$proThumb' WHERE id = $propertyId";
                                $db->query($sqlUpdateProperty);
                                $checkFirstImage++;
                            }
                            $slideImage = $upload_url."/".$filename;
                            $db->query("INSERT INTO property_image (property_id, image) VALUES ($propertyId, '$slideImage')");
                            for($s=0;$s<count($thumbSize);$s++) {// start create thumbnail
                                $upload_dir_thumb = $upload_dir.'/thumb-'.$thumbSize[$s];
                                if (!file_exists($upload_dir_thumb)) {
                                    if(!mkdir($upload_dir_thumb, 0777,true)) {
                                        $CONFIG["error_message"] .= "<li>Can not create thumb directory, please check permission.</li>";
                                    }
                                }
                                $wh = explode('-',$thumbSize[$s]);
                                $thumbnail_width = $wh[0];
                                $thumbnail_heigh = $wh[1];
                                //create thumb
                                include_once (SITE_LIBRARY_DIR."/phpThumb/ThumbLib.inc.php");
                                $options = array('resizeUp' => true, 'jpegQuality'=>88);
                                $thumb = PhpThumbFactory::create($upload_dir."/".$filename, $options);
                                $thumb->adaptiveResize($thumbnail_width+5, $thumbnail_heigh+5);
                                $thumb->cropFromCenter($thumbnail_width, $thumbnail_heigh);
                                $thumb->save($upload_dir_thumb.'/'.$filename,'jpg');
                            }
                        }else {
                            $CONFIG["error_message"] .= "<li>Error, Can not upload image: ".$images["name"][$i].'</li>';
                        }
                    }else {
                        $CONFIG["error_message"] .= "<li>Invalid file ".$images['name'][$i].'</li>';
                    }
                }
            }
            server_redirect($url);

        }
    }
}
function getPropertyStepsData() {
    global $db;
    if(isset($_SESSION['mem_property_id']) && intval($_SESSION['mem_property_id'])>0) {
        //$data = array('type','cat_id','title','geo_id','price');
        //$sqlFields = implode(',', $data);
        $sql = "SELECT * FROM property WHERE 1 AND id=".$_SESSION['mem_property_id']." AND member_id=".$_SESSION['login']['id'];
        $rs = $db->query_first($sql);
        return $rs;
    }
}

function getPropertyStepImages() {
    global $db;
    if(isset($_SESSION['mem_property_id']) && intval($_SESSION['mem_property_id'])>0) {
        $sql = "SELECT * FROM property_image WHERE 1 AND property_id=".$_SESSION['mem_property_id'];
        $rs = $db->query($sql);
        return $rs;
    }
}

function getPropertyImageNameByImageId($id) {
    global $db;
    $rs = $db->query_first("SELECT id,image FROM property_image WHERE id=$id");
    if(intval($rs['id'])>0) {
        return basename($rs['image']);
    }else {
        return false;
    }
}

//function getMemberIdFromImageName($imageName) {
//    $piesImageName = explode('/', $imageName);
//    $arrMem = explode('-', $piesImageName[4]);
//    return $arrMem[1];
//}
?>